//
//  ZHCZViewController.m
//  firstpoint
//
//  Created by 泽中 on 2017/7/19.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "ZHCZViewController.h"
#import "BinDingTextView.h"
#import "ChongZhiFangShiView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "RSADataSigner.h"
@interface ZHCZViewController ()
{
UIButton*yuanbaoBtn;
UIButton*jinbiBtn;
    UIView*yuanbaoView;
    UIView*jinbiView;
    
    UITextField*yuanbaoText;
    UITextField*jinbiText;
}
@property (nonatomic,strong)NSString *DDIDstring;
@property (nonatomic,strong)NSString *chongzhileixing;
@property (nonatomic,strong)NSString *dingDanStr;
@end

@implementation ZHCZViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"账户充值";
    self.view.backgroundColor=LRRGBColor(235, 240, 242);

    [self setButton];
    [self setView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainVCReceivedNotification:) name:@"tongzhi" object:nil];
    
}
-(void)setView
{   //元宝
    yuanbaoView=[[UIView alloc]initWithFrame:CGRectMake(20, 130, width_screen-40, 350)];
    yuanbaoView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:yuanbaoView];
    
    BinDingTextView*duihuanNumView=[[BinDingTextView alloc]initWithFrame:CGRectMake(20, 20, yuanbaoView.mj_w-40, 60)];
    duihuanNumView.textField.placeholder=@"请输入充值的金额";
    duihuanNumView.textField.font=[UIFont systemFontOfSize:25];
    duihuanNumView.titleLab.text=@"充值金额";
    [yuanbaoView addSubview:duihuanNumView];
    
    ChongZhiFangShiView*wechatView=[[ChongZhiFangShiView alloc]initWithFrame:CGRectMake(0, 110, yuanbaoView.mj_w, 50)];
    wechatView.imgView.image=[UIImage imageNamed:@"shdwx"];
    wechatView.label.text=@"微信支付";
    [wechatView.button setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
    [yuanbaoView addSubview:wechatView];
    
    ChongZhiFangShiView*aliPayView=[[ChongZhiFangShiView alloc]initWithFrame:CGRectMake(0, 160, yuanbaoView.mj_w, 50)];
    aliPayView.imgView.image=[UIImage imageNamed:@"shdbdzfb"];
    aliPayView.label.text=@"支付宝支付";
    [aliPayView.button setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
    [yuanbaoView addSubview:aliPayView];

   
    UIButton*duihuanYuanBaoButton=[UIButton buttonWithType:UIButtonTypeCustom];
    duihuanYuanBaoButton.frame=CGRectMake(20, aliPayView.mj_h+aliPayView.mj_y+30, yuanbaoView.mj_w-40, 50);
    duihuanYuanBaoButton.backgroundColor=[UIColor orangeColor];
    [duihuanYuanBaoButton setTitle:@"确认充值" forState:0];
    duihuanYuanBaoButton.layer.cornerRadius=5;
    [yuanbaoView addSubview:duihuanYuanBaoButton];
    
    //金币
    jinbiView=[[UIView alloc]initWithFrame:CGRectMake(20, 130, width_screen-40, 350)];
    jinbiView.hidden=YES;
    jinbiView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:jinbiView];
    
    
    BinDingTextView*duihuanNumView2=[[BinDingTextView alloc]initWithFrame:CGRectMake(20, 20, yuanbaoView.mj_w-40, 60)];
    duihuanNumView2.textField.placeholder=@"请输入充值的金额";
    duihuanNumView2.textField.font=[UIFont systemFontOfSize:25];
    
    duihuanNumView2.titleLab.text=@"充值金额";
    [jinbiView addSubview:duihuanNumView2];
    jinbiText = duihuanNumView2.textField;
    
    
    ChongZhiFangShiView*wechatView2=[[ChongZhiFangShiView alloc]initWithFrame:CGRectMake(0, 110, yuanbaoView.mj_w, 50)];
    wechatView2.imgView.image=[UIImage imageNamed:@"shdwx"];
    wechatView2.label.text=@"微信支付";
    [wechatView2.button setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
    [wechatView2.button addTarget:self action:@selector(xuanzhongbtnClciek:) forControlEvents:UIControlEventTouchUpInside];
    wechatView2.button.tag = 10001;
    [jinbiView addSubview:wechatView2];
    
    ChongZhiFangShiView*aliPayView2=[[ChongZhiFangShiView alloc]initWithFrame:CGRectMake(0, 160, yuanbaoView.mj_w, 50)];
    aliPayView2.imgView.image=[UIImage imageNamed:@"shdbdzfb"];
    aliPayView2.label.text=@"支付宝支付";
    [aliPayView2.button addTarget:self action:@selector(xuanzhongbtnClciek:) forControlEvents:UIControlEventTouchUpInside];
    aliPayView2.button.tag = 10000;
    [aliPayView2.button setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
    [jinbiView addSubview:aliPayView2];

   
    UIButton*duihuanJinBiButton=[UIButton buttonWithType:UIButtonTypeCustom];
    duihuanJinBiButton.frame=CGRectMake(20, aliPayView2.mj_h+aliPayView2.mj_y+30, yuanbaoView.mj_w-40, 50);
    duihuanJinBiButton.backgroundColor=[UIColor orangeColor];
    [duihuanJinBiButton setTitle:@"确认充值" forState:0];
    duihuanJinBiButton.layer.cornerRadius=5;
    [duihuanJinBiButton addTarget:self action:@selector(duihuanbtnClicke) forControlEvents:UIControlEventTouchUpInside];
    [jinbiView addSubview:duihuanJinBiButton];
    
}
-(void)xuanzhongbtnClciek:(UIButton *)button{
    UIButton *button1 = [self.view viewWithTag:10000];
    UIButton *button2 = [self.view viewWithTag:10001];
    if (button.tag==10000) {
        [button1 setImage:[UIImage imageNamed:@"gwcxz"] forState:0];
        [button2 setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
    }else{
        [button1 setImage:[UIImage imageNamed:@"gwcwxz"] forState:0];
        [button2 setImage:[UIImage imageNamed:@"gwcxz"] forState:0];
    }
}
-(void)setButton
{
    yuanbaoBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    yuanbaoBtn.backgroundColor=LRRGBColor(23, 146, 211);
    [yuanbaoBtn setTitle:@"兑换元宝" forState:0];
    yuanbaoBtn.frame=CGRectMake(20, 84, (width_screen-40)/2, 45);
    [yuanbaoBtn addTarget:self action:@selector(yuanbaoClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:yuanbaoBtn];
    
    jinbiBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [jinbiBtn addTarget:self action:@selector(jinbiClick) forControlEvents:UIControlEventTouchUpInside];
    
    jinbiBtn.backgroundColor=[UIColor whiteColor];
    [jinbiBtn setTitle:@"兑换金币" forState:0];
    [jinbiBtn setTitleColor:LRRGBColor(23, 146, 211) forState:0];
    jinbiBtn.frame=CGRectMake(20+(width_screen-40)/2, 84, (width_screen-40)/2, 45);
    [self.view addSubview:jinbiBtn];
}
-(void)yuanbaoClick
{
    yuanbaoBtn.backgroundColor=LRRGBColor(23, 146, 211);
    [yuanbaoBtn setTitleColor:[UIColor whiteColor] forState:0];
    jinbiBtn.backgroundColor=[UIColor whiteColor];
    [jinbiBtn setTitleColor:LRRGBColor(23, 146, 211) forState:0];
    jinbiView.hidden=YES;
    yuanbaoView.hidden=NO;
}

-(void)jinbiClick
{ jinbiBtn.backgroundColor=LRRGBColor(23, 146, 211);
    [jinbiBtn setTitleColor:[UIColor whiteColor] forState:0];
    yuanbaoBtn.backgroundColor=[UIColor whiteColor];
    [yuanbaoBtn setTitleColor:LRRGBColor(23, 146, 211) forState:0];
    jinbiView.hidden=NO;
    yuanbaoView.hidden=YES;
}
//duihuan
-(void)duihuanbtnClicke{
//    [self huoquDingdanXingXiURL];
    [self doAlipayPay];
}
#pragma mark -
#pragma mark   ==============点击订单模拟支付行为==============
//
//选中商品调用支付宝极简支付
//
- (void)doAlipayPay
{
    //重要说明
    //这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    //真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    //防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2017071807798709";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSortoIEnh+7BOf+HKYvJV5kVasqkede3XqsoEAjVe6It2EgWcYdKxYwdCfiTriBtUGRrKeMc8c6JZX93on9kEVQ2LNwMnI1z+T5yLpHraH3AXFpavYeGUBx5A6N5VmudgWgNNBgBNUKQJ2ctZKMvADN9D8ezZtGGB1Y+YRL76RNXtlH0Hqh5s7avtCUdf/mduqUcMyy4x2f1CfNu+ddJJt5avy1GNHlIowOKh58A3OTEayaDoyTYyM36wUIQVJaQBt5tiweQWh6i4n8C48LnrDUJfnP876kdDv4wzZfjGiGgQdrbTG2ojE+s74G/rqwy4Wg5N1rji0YVzFlM3ZzEPAgMBAAECggEAUckT79K6gqGHx3DKNcCUW1bQ7fJiI0wxOS3X+P5mWCYpytPobz2cbzXFkc+btga2/2P1LmLI9S2lqmWu9pVZTHJH2JL5XjX6IxmyPayinNAWC7qclvtn/tEtjZSUlXiNfo8V8jrbpkPJCnmAUp1PbzF+wX3I1fAmxmyf55TIU/uCl85fxae64SQOllfZJvfZdLZj8wwfeB5W9cGURKzEzhD3QMphPMsdy4jEMksESrfURmcZ1qJpylznR9mcl/JHMkmn2eUaPP6/8MKdW2/Obfhtm7DivH3OTNjQgXFC/1UVeBsQs87tlg3A1dKBmJbEzCPvdPBr3nSN9AHcByRY6QKBgQDDJYVsMKk0hExsOuZtKeTSinOXopJcQ5H5wnN3DDUpvHXfXqUJ20jv9jZdbbCS9Z66w7+PoZMqcdgvL6OFtl7zmyK8I4jI1O1Y4GmNB/mQ/Y7xUkEYGmgfwec9Qp9ziniClulbnYefRfQjcbSZg/ARPj75Ww5o4csYKNtn3RKMdQKBgQDAXJqbZ4u/d93TAVmaPgyGKLnvasgfZSdOgBFkJfNbaoOIc3n1QUGedxoJ3UlG3O8NClHt1AIgMj5DLZuPCcg+K0/Ll1lLM6UTpxXIIXZGXXeDGwbD1JlPODrlAqZtXMgyFch9CYcXn2DvXqExVp5D4U3+SSv+vi/9cI4F4dim8wKBgA/sq+qcPfKPKT1bwRn/ZTDZI32oQpFM4kijWZDJaj0xp9zGeGlJf7Y1PVJ6dQJJEN7kwmkSIlRAXgfbt1hd/Xmbm0YHEE5zMbsi9PoRQIhYaKXAtJcm8IBG7nvNR/3BuvvNHNXhEQQqTTXnPXmZjqmZjsICcDaW1l/uVZkwLSdRAoGARMnYz/H7W4D15lr5O9ssh11RAHjjD7cQk1Xg4jtgBzTTzJve5QFtAcn9mcF0Ts76/WLPYYkLKZBOC5/nnQMWhITgiCGbYPUa9ygs9eBhd1A9SLkFdko0eMvW48ZK1Zj0TlTT2ULq+FuaQn9IjWg4OHX9eg2YmgRRDQSPBTN6UlkCgYEAvkbIZc6Xl4diso0Kb3yLsq3cH/uSs/abTzulVo0HNGuhBTzq7vtNNOYU0RSkrXFGq+LBKHJNQ36Y2gvkPmxoRhRxFVDXQw9jT4qtt4AXmsPxxaiv2s33eYfkggpWxxju+6bQZfFoE7NxqJo80M+i5cQMxGmQkesm4yGhGpa2b84=";
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少appId或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    order.biz_content.body = @"元点商城";
    order.biz_content.subject = @"元点商城充值";
    order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID（由商家自行制定）
    _DDIDstring = order.biz_content.out_trade_no;
    [USER_D setObject:_DDIDstring forKey:@"订单ID"];
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    float jg= [jinbiText.text floatValue];
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", jg]; //商品价格
    //    order.notify_url = @"";
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    RSADataSigner* signer = [[RSADataSigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"yuandiangeren";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            NSInteger orderState=[resultDic[@"resultStatus"] integerValue];
            if (orderState==9000) {
                
                //成功
                [self alipaySccesswith:@"20"];//
                
            }else{
                NSString *returnStr;
                switch (orderState) {
                    case 8000:
                        returnStr=@"订单正在处理中";
                        break;
                    case 4000:
                        returnStr=@"订单支付失败";
                        break;
                    case 6001:
                        returnStr=@"订单取消";
                        break;
                    case 6002:
                        returnStr=@"网络连接出错";
                        break;
                        
                    default:
                        break;
                }
                UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:returnStr delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alertview show];
            }
            
        }];
    }
}
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
//网页支付宝 支付成功
-(void)alipaySccesswith:(NSString *)string{
    NSLog(@"%@",jinbiText.text);
    
    NSLog(@"%@",[USER_D objectForKey:@"订单ID"]);
    __weak typeof(self) weakself = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"recharge/payment.api?access_token="),NSUD_Obj(@"token")];
    [HTTPURL postRequest:url parameters:@{@"sign":userid,@"sign_type":jinbiText.text,@"trade_no":@"元点充值",@"out_trade_no":@"元点充值",@"timestamp":@"1007",@"total_amount":@"1001"} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retFlag"]intValue]==1) {
            
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
    
}
//获取订单
-(void)huoquDingdanXingXiURL{
    __weak typeof(self) waekself = self;
    NSLog(@"%@",userid);
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"recharge/payment.api?access_token="),NSUD_Obj(@"token")];
    [HTTPURL postRequest:url parameters:@{@"userId":userid,@"total_amount":jinbiText.text,@"subject":@"元点充值",@"body":@"元点充值",@"payType":@"1007",@"rechargeType":@"1001"} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retFlag"]intValue]==1) {
          
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];

}
//响应通知绑定的方法的时候，传递过来的参数是绑定这个方法的通知的对象
-(void)mainVCReceivedNotification:(NSNotification *)sender{
    NSDictionary *dic = [sender userInfo];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
